<template>
  <div class="tinymce-editor" :style="{ width: containerWidth }">
    <textarea :id="tinymceId" ref="elRef"></textarea>
  </div>
</template>

<script>
import tinymce from 'tinymce/tinymce'
import 'tinymce/themes/silver/theme'
import 'tinymce/icons/default'
import 'tinymce/plugins/image'
import 'tinymce/plugins/link'
import 'tinymce/plugins/code'
import 'tinymce/plugins/table'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/wordcount'
import 'tinymce/plugins/preview'
import 'tinymce/plugins/fullscreen'
import 'tinymce/plugins/paste'
import request from '@/utils/request'

export default {
  name: 'Tinymce',
  props: {
    value: {
      type: String,
      default: ''
    },
    height: {
      type: [Number, String],
      default: 400
    },
    width: {
      type: [Number, String],
      default: 'auto'
    }
  },
  data() {
    return {
      tinymceId: 'tinymce-' + Date.now() + Math.random().toString(36).substr(2, 9),
      editor: null,
      isInitialized: false
    }
  },
  computed: {
    containerWidth() {
      const width = this.width
      if (typeof width === 'number') {
        return `${width}px`
      }
      return width
    }
  },
  watch: {
    value(newVal) {
      if (this.editor && this.isInitialized && newVal !== this.editor.getContent()) {
        this.editor.setContent(newVal || '')
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initEditor()
    })
  },
  beforeDestroy() {
    this.destroyEditor()
  },
  methods: {
    initEditor() {
      const self = this
      tinymce.init({
        selector: `#${this.tinymceId}`,
        height: this.height,
        menubar: false,
        plugins: 'image link code table lists wordcount preview fullscreen paste',
        toolbar: 'undo redo | formatselect | bold italic | alignleft aligncenter alignright | bullist numlist | link image | code fullscreen',
        branding: false,
        promotion: false,
        statusbar: true,
        elementpath: false,
        resize: true,
        // 配置语言
        language: 'zh_CN',
        language_url: '/resource/tinymce/langs/zh_CN.js',
        // 配置皮肤路径
        skin_url: '/resource/tinymce/skins/ui/oxide',
        content_css: '/resource/tinymce/skins/content/default/content.css',
        // 禁用自动保存
        auto_focus: false,
        // 内容样式
        content_style: `
          body { 
            font-family: '微软雅黑', 'Microsoft YaHei', Arial, sans-serif; 
            font-size: 14px; 
            line-height: 1.6;
            padding: 10px;
          }
          img { max-width: 100%; height: auto; }
        `,
        // 图片上传
        images_upload_handler: (blobInfo, success, failure) => {
          const formData = new FormData()
          formData.append('file', blobInfo.blob(), blobInfo.filename())
          
          request({
            url: '/common/upload',
            method: 'post',
            data: formData,
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }).then(res => {
            if (res.code === 200) {
              success(process.env.VUE_APP_BASE_API + res.fileName)
            } else {
              failure('上传失败: ' + (res.msg || '未知错误'))
            }
          }).catch(err => {
            failure('上传失败: ' + err.message)
          })
        },
        // 初始化完成
        init_instance_callback: (editor) => {
          self.editor = editor
          self.isInitialized = true
          
          // 设置初始内容
          if (self.value) {
            editor.setContent(self.value)
          }
          
          // 监听内容变化
          editor.on('input change undo redo', () => {
            const content = editor.getContent()
            self.$emit('input', content)
            self.$emit('change', content)
          })
          
          self.$emit('init', editor)
        }
      }).catch(err => {
        console.error('TinyMCE初始化失败:', err)
        // 如果是皮肤加载错误，尝试不使用皮肤
        if (err && err.message && err.message.includes('skin')) {
          this.initEditorWithoutSkin()
        } else {
          this.$message.error('TinyMCE初始化失败，请刷新页面重试')
          this.$emit('init-error', err)
        }
      })
    },
    // 不使用皮肤的初始化方法（降级方案）
    initEditorWithoutSkin() {
      const self = this
      tinymce.init({
        selector: `#${this.tinymceId}`,
        height: this.height,
        menubar: false,
        plugins: 'image link code table lists wordcount preview fullscreen paste',
        toolbar: 'undo redo | formatselect | bold italic | alignleft aligncenter alignright | bullist numlist | link image | code fullscreen',
        branding: false,
        promotion: false,
        statusbar: false,
        // 不使用皮肤
        skin: false,
        content_css: false,
        content_style: `
          body { 
            font-family: '微软雅黑', 'Microsoft YaHei', Arial, sans-serif; 
            font-size: 14px; 
            line-height: 1.6;
            padding: 10px;
            border: 1px solid #ddd;
            min-height: ${this.height - 100}px;
          }
          img { max-width: 100%; height: auto; }
        `,
        images_upload_handler: (blobInfo, success, failure) => {
          const formData = new FormData()
          formData.append('file', blobInfo.blob(), blobInfo.filename())
          
          request({
            url: '/common/upload',
            method: 'post',
            data: formData,
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }).then(res => {
            if (res.code === 200) {
              success(process.env.VUE_APP_BASE_API + res.fileName)
            } else {
              failure('上传失败: ' + (res.msg || '未知错误'))
            }
          }).catch(err => {
            failure('上传失败: ' + err.message)
          })
        },
        init_instance_callback: (editor) => {
          self.editor = editor
          self.isInitialized = true
          
          if (self.value) {
            editor.setContent(self.value)
          }
          
          editor.on('input change undo redo', () => {
            const content = editor.getContent()
            self.$emit('input', content)
            self.$emit('change', content)
          })
          
          self.$emit('init', editor)
        }
      })
    },
    destroyEditor() {
      if (this.editor) {
        tinymce.remove(`#${this.tinymceId}`)
        this.editor = null
        this.isInitialized = false
      }
    },
    // 获取内容
    getContent() {
      return this.editor ? this.editor.getContent() : ''
    },
    // 设置内容
    setContent(content) {
      if (this.editor && this.isInitialized) {
        this.editor.setContent(content || '')
      }
    }
  }
}
</script>

<style scoped>
.tinymce-editor {
  position: relative;
  line-height: normal;
}
</style>
